import { Fragment} from 'react'
import { Form } from 'tdesign-react'
import VariableForm from './VariableForm'
import Input from './Input'

import './index.less'

import type { InternalFormInstance } from 'tdesign-react/es/form'
import type { FormListType, FormListItemType, FormInputItemPropsType } from '@/types/form.type'

type PropsType = {
  form: InternalFormInstance
  formList: Expand<FormListType>
  footer?: React.ReactNode
  layout?: 'vertical' | 'inline' | undefined
  onSubmit: (values: any) => void
  onReset?: () => void
  labelWidth?: number
}

const FormList = (props: PropsType) => {

  const {
    form,
    formList,
    footer,
    layout = 'vertical',
    onSubmit,
    onReset,
    ...extraProps
  } = props

  const renderInput = (
    { label, name, formItemProps = {}, formFieldProps = {}, }: FormInputItemPropsType,
    index: number
  ): React.ReactNode => {
    const { rules, tooltip, intro, ...formItemohtherProps } = formItemProps
    const {...formFieldohtherProps } = formFieldProps
    return <Fragment key={`${name}-${index}`}>
      <Form.FormItem
        label={label}
        rules={rules}
        name={name}
        {...formItemohtherProps}
      >
        <Input
          label={label}
          name={name}
          {...formFieldohtherProps}
        />
      </Form.FormItem>
    </Fragment>
  }

  return <Form
    className={`c-form-list`}
    form={form as any}
    onSubmit={onSubmit}
    layout={layout}
    labelAlign='right'
    preventSubmitDefault
    resetType='empty'
    showErrorMessage
    {...extraProps}
    // initialValues={initialValues}
  >
    {formList.map((item: FormListItemType, index: number) => {
      switch (item.type) {
        case 'input':
          return renderInput(item, index)
        default:
          return <Fragment key={`${item.name}-${index}`}></Fragment>
      }
    })}
    <Form.FormItem className='c-form-list__footer'>
      {footer}
    </Form.FormItem>
  </Form>
}

export {
  FormList,
  VariableForm,
  Form,
}

